package com.lzq.mq.broker.core;


import com.lzq.mq.broker.cache.CommonCache;
import com.lzq.mq.common.constants.BrokerConstants;
import com.lzq.mq.common.dto.MessageDTO;

import java.io.IOException;

/**
 * 提供操作CommitLog的最外层API
 */
public class CommitLogAppendHandler {


    public CommitLogAppendHandler() {
    }

    /**
     * 将topic的commitLog文件映射成MMap, 并加入到map中
     * 方便后续通过topicName获取映射操作文件
     * @param topicName topic的名称
     */
    public void prepareMMapLoading(String topicName) {
        CommitLogMMapFileModel mapFileModel = new CommitLogMMapFileModel();
        try {
            mapFileModel.loadFileInMMap(topicName, 0, BrokerConstants.COMMITLOG_DEFAULT_MMAP_SIZE);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        CommonCache.getCommitLogMMapFileModelManager().put(topicName, mapFileModel);
    }


    /**
     * 追加消息
     * @param messageDTO 消息
     */
    public void appendMsg(MessageDTO messageDTO) throws IOException {
        CommitLogMMapFileModel mapFileModel = CommonCache.getCommitLogMMapFileModelManager().get(messageDTO.getTopic());
        if (mapFileModel == null) {
            throw new RuntimeException("推送的主题非法!");
        }
        mapFileModel.writeContent(messageDTO, true);        // todo 强制刷盘
    }

    /**
     * 读取消息
     * @param topic 主题
     * @return 消息内容
     */
    public byte[] readMsg(String topic) {
        CommitLogMMapFileModel mapFileModel = CommonCache.getCommitLogMMapFileModelManager().get(topic);
        if(mapFileModel==null) {
            throw new RuntimeException("topic is invalid!");
        }
        return mapFileModel.readContent(0,1000);
    }

}
